#!/bin/bash

P=$1
BZ=$2
tag=$3

if [ $# -lt 3 ]; then
    echo "$0 <patch> <bugzilla string> <upstream tag>"
    exit 1
fi

git am ${P}

if [ $? -ne 0 ]; then
    git am --abort
    echo "${P}" >> failed-${tag}.list
    
    #sbj=$(sed -n '4p' ${P} | sed -r 's@^Subject:[^]]+] @@')
    HS=$(head -n 1 ${P} | awk '{print $2}')
    hs=$(echo $HS | cut -c -12)
    sbj=$(git -C /work/zxq/linux-stable show -s --format="%s" ${HS})
    r=$(git log --pretty=format:"%s" | grep "${sbj}")
    echo
    if [ -n "$r" ]; then
        echo "already merged: $r"
        echo
        echo "${hs}: ${sbj}" >> merged-${tag}.list
        exit 0
    else
        echo "Confilct, please FIX IT !!!"
        echo "${hs}: ${sbj}" >> conflict-${tag}.list
    fi
    echo
    echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ FAILED @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"

    exit 1
fi

commit=$(head -n 1 ${P} | awk '{print $2}')
./mod_commit_msg.sh ${commit} ${BZ} ${tag}
